package com.com.corejavalearnings.collections;

import java.util.Arrays;
import java.util.List;

/**
 * Created by User on 07/07/2015.
 */
public class ViewsOfCollections {
    public static void main(String[] args) {
        Person sam = new  Person(123, "Sam", 2340.45);
        Person robert = new  Person(124, "Robert", 2340.45);
        Person joe = new  Person(125, "Joe", 2340.45);

        Person[] persons = {sam, robert, joe};
        List<Person> personsView = Arrays.asList(persons);

        //http://softwarecave.org/2014/03/19/views-in-java-collections-framework/
        /*For obvious reasons the returned collection is immutable which means
        it is impossible to add or remove elements from it. But it is still possible to
        modify the elements inside the view using get() or set() methods.
        */
        for(Person person : personsView)
        {
            //Throw UnSupportedOperationException
            //personsView.add(new Person(126, "Kim", 544.0));

            //Throw UnSupportedOperationException
            //personsView.remove(new Person(125, "Joe", 2340.45));

            person.setBalance(0.0);
            System.out.println(person);
        }


        sam.setBalance(23.0);
        for(Person person : personsView)
        {
          System.out.println(person);
        }
    }
}

class Person{
    int sin;
    String name;
    Double balance;

    Person(int sin, String name, Double balance) {
        this.sin = sin;
        this.name = name;
        this.balance = balance;
    }

    public int getSin() {
        return sin;
    }

    public void setSin(int sin) {
        this.sin = sin;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Double getBalance() {
        return balance;
    }

    public void setBalance(Double balance) {
        this.balance = balance;
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;

        Person person = (Person) o;

        if (sin != person.sin) return false;
        if (balance != null ? !balance.equals(person.balance) : person.balance != null) return false;
        if (name != null ? !name.equals(person.name) : person.name != null) return false;

        return true;
    }

    @Override
    public int hashCode() {
        int result = sin;
        result = 31 * result + (name != null ? name.hashCode() : 0);
        result = 31 * result + (balance != null ? balance.hashCode() : 0);
        return result;
    }

    @Override
    public String toString() {
        return "Person{" +
                "sin=" + sin +
                ", name='" + name + '\'' +
                ", balance=" + balance +
                '}';
    }
}

